<?php

class NoticeModel extends Model
{
    /**
     * 使用的表名称.
     *
     * @var string
     */
    protected $tableName = 'notice';

    /**
     * 字段列表.
     *
     * @var unknown_type
     */
    protected $fields = array(
        0          => 'notice_id',
        1          => 'title',
        2          => 'pictures',
        3          => 'state',
        4          => 'is_top',
        5          => 'hits',
        6          => 'isdel',
        7          => 'created',
        8          => 'updated',
        9          => 'uid',
        10         => 'sort',
        11         =>'is_audit',
        12         =>'content',
        '_autoinc' => true,
        '_pk'      => 'notice_id',
    );



    /**
     * 获取状态
     *
     * @param int $state 状态ID
     *
     * @return mixed
     */
    public function getState($state = null)
    {
        $states = array(
            1 => '显示',
            0 => '不显示',
        );
        if ($state === null) {
            return $states;
        }

        return isset($states[$state]) ? $states[$state] : '';
    }

    /**
     * 更新信息.
     *
     * @param array $data 字段值
     *
     * @return mixed
     */
    public function setNews($uid)
    {
        $ret = array('ret' => false, 'msg' => '更新信息失败');
        $news = D('News');
        if ($news->create()) {
            $news->uid = ($uid) ? $uid : 0;
            if ($news->news_id) {
                $result = $news->save();
            } else {
                $result = $news->add();
            }
            if ($result) {
                $ret = array('ret' => true, 'msg' => '成功更新信息');
            } else {
                $ret['msg'] = $news->getError();
            }
        } else {
            $ret['msg'] = $news->getError();
        }

        return $ret;
    }

    /**
     * 获取子分类的ID串.
     *
     * @param int $pid
     *
     * @return array
     */
    private function _getChildTids($pid)
    {
        static $_result = array();
        if (isset($_result[$pid])) {
            return $_result[$pid];
        }
        //查找
        $child = model('CategoryTree')->setTable('news_category')->getNetworkList($pid);
        $ids = array_keys($child);
        $_result[$pid] = ($ids) ? $ids : array();

        return $ids;
    }

    /**
     * 前台列表获取.
     */
    public function getList($limit = 20, $notice_id = 0, $keywords = '', $order = '', $findPage = true)
    {
        $map = array();
        $map['state'] = array('GT', 0);

        if ($keywords) {
            $map['name'] = array('like', '%'.$keywords.'%');
        }
        if ($order == '') {
            $order = 'is_top desc,notice_id desc';
        }
        if ($notice_id > 0) {
            $map['notice_id'] = $notice_id;
        }
        $this->where($map)->order($order);
        if ($findPage) {
            $list = $this->findPage($limit);
            $data = $list['data'];
        } else {
            $data = $this->findAll(array('limit' => $limit));
        }
        foreach ($data as $k => $v) {
            $thumb = APPS_URL.'/'.APP_NAME.'/_static/nopic.jpg';
            if (empty($v['picture'])) {
                $attach = model('Attach')->getAttachById($v['picture']);
                if ($attach) {
                    $thumb = getImageUrl($attach['save_path'].$attach['save_name'], 100, 100);
                }
                $v['picture'] = $thumb;
            }
            //$data[$k]['image'] = $thumb;
            //$data[$k]['title_intro'] = msubstr($v['news_title'], 0, 30);
            //$data[$k]['content_intro'] = msubstr(strip_tags($v['news_content']), 0, 100);
            //获取评论数量
            //$data[$k]['comment_count'] = model('Comment')->where(array('app' => 'news', 'table' => 'news', 'is_del' => 0, 'row_id' => $v['news_id']))->count();
        }
        if ($findPage) {
            $list['data'] = $data;

            return $list;
        } else {
            return $data;
        }
    }

    /**
     * 根据ID获取资料.
     *
     * @param int  $id
     * @param bool $is_admin 是否是后台
     *
     * @return array
     */
    public function getOneyById($id, $is_admin = false, $update_hits = false)
    {
        $map = array(
            'notice_id' => $id,
        );
        if ($is_admin == false) {
            $map['state'] = array('GT', 0);
        }
        $v = $this->where($map)->find();
        if ($v) {
            $v['attachId'] = $v['picture'];
            $thumb = APPS_URL.'/'.APP_NAME.'/_static/nopic.jpg';
            if ($v['image']) {
                $attach = model('Attach')->getAttachById($v['picture']);
                if ($attach) {
                    $thumb = getImageUrl($attach['save_path'].$attach['save_name'], 100, 100);
                }
            }
            $v['picture'] = $thumb;
            //更新浏览量
            if ($is_admin === false && $update_hits == true) {
                $this->setInc('hits', array('notice_id' => $id), 1);
            }
        }

        return $v;
    }

    /**
     * 获取子分类的ID串.
     *
     * @param int $pid
     *
     * @return array
     */
    private function getChildTids($pid)
    {
        static $_result = array();
        if (isset($_result[$pid])) {
            return $_result[$pid];
        }
        //查找
        $child = model('CategoryTree')->setTable('news_category')->getNetworkList($pid);
        $ids = array_keys($child);
        $_result[$pid] = ($ids) ? $ids : array();

        return $ids;
    }

    /**
     * 获取信息.
     *
     * @param int $id
     *
     * @return mixed
     */
    public function getSourceInfo($id)
    {
        $find = $this->getOneyById($id);
        if ($find) {
            $info = array('source_user_info' => '');
            if ($find['uid']) {
                $info['source_user_info'] = model('User')->getUserInfo($find['uid']);
            }
            $info['source_url'] = U('news/Index/detail', array('id' => $id));
            $info['source_body'] = $find['news_title'].'<a class="ico-details" href="'.U('news/Index/show', array('id' => $id)).'"></a>';

            return $info;
        }

        return false;
    }

    /**
     * 删除分类后的回调.
     *
     * @param int $cid
     *
     * @return bool
     */
    public function deleteAssociatedData($cid)
    {
        return $this->where(array('type_id' => $cid))->delete();
    }

    public function doEditNotice($notice_id, $type, $title, $uid = null)
    {
        $return = array('status' => '0');
        if (empty($notice_id)) {
            //$return['data'] = '分享ID不能为空！';
        } else {
            $map['notice_id'] = is_array($notice_id) ? array('IN', $notice_id) : intval($notice_id);
            $save['is_del'] = $type == 'delNotice' ? 1 : 0;

            if ($type == 'deleteNotice') {
                $noticeArr = is_array($notice_id) ? $notice_id : explode(',', $notice_id);
                // 取消分享收藏
                foreach ($noticeArr as $sid) {
                    $notice = $this->where('notice_id='.$sid)->find();
                    model('Collection')->delBynotice($sid, 'notice');
                    // model('Collection')->delCollection($sid, 'notice', $notice['uid']);
                }
                // 彻底删除分享
                $res = $this->where($map)->delete();
                // 删除分享相关信息
                if ($res) {
                    $this->_deletenoticeAttach($notice_id, 'deleteAttach');
                }
            } else {
                $ids = !is_array($notice_id) ? array($notice_id) : $notice_id;
                $noticeList = $this->getnotices($ids);
                $res = $this->where($map)->save($save);
                if ($type == 'noticeRecover') {
                    // 添加分享数
                    foreach ($noticeList as $v) {
                        model('UserData')->setUid($v['user_info']['uid'])->updateKey('notice_count', 1);
                        model('UserData')->setUid($v['user_info']['uid'])->updateKey('weibo_count', 1);
                    }
                    $this->_deletenoticeAttach($ids, 'recoverAttach');
                } else {
                    // 减少分享数
                    foreach ($noticeList as $v) {
                        model('UserData')->setUid($v['user_info']['uid'])->updateKey('notice_count', -1);
                        model('UserData')->setUid($v['user_info']['uid'])->updateKey('weibo_count', -1);
                    }
                    $this->_deletenoticeAttach($ids, 'delAttach');
                    // 删除频道相应分享
                    $channelMap['notice_id'] = array('IN', $ids);
                    D('channel')->where($channelMap)->delete();
                }
                model('Collection')->delBynotice($ids, 'notice');
                $this->cleanCache($ids);        // 删除分享缓存信息
                // 资源分享缓存相关分享
                foreach ($noticeList as $item) {
                    if ($item['app'] == 'public') {
                        $sids = $this->where('app_row_id='.$item['notice_id'])->getAsFieldArray('notice_id');
                        $this->cleanCache($sids);
                    } else {
                        $tmp_map['app'] = $item['app'];
                        $tmp_map['app_row_id'] = $item['app_row_id'];
                        $sids = $this->where($tmp_map)->getAsFieldArray('notice_id');
                        $this->cleanCache($sids);
                    }
                }
            }
            // 删除评论信息
            $cmap['app'] = 'Public';
            $cmap['table'] = 'notice';
            $cmap['row_id'] = is_array($notice_id) ? array('IN', $notice_id) : intval($notice_id);
            $commentIds = model('Comment')->where($cmap)->getAsFieldArray('comment_id');
            model('Comment')->setAppName('Public')->setAppTable('notice')->deleteComment($commentIds);
            if ($res) {
                // TODO:是否记录知识，以及后期缓存处理
                $return = array('status' => 1);
                //添加积分
                model('Credit')->setUserCredit($uid, 'delete_weibo');
            }
        }

        return $return;
    }
}
